package com.zhentao.equipment.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhentao.equipment.mapper.DeviceConfigMapper;
import com.zhentao.pojo.DeviceConfig;
import com.zhentao.util.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 设备配置服务：支持读取和批量写入，带Redis缓存
 */
@Service
public class DeviceConfigService {

    @Autowired
    private DeviceConfigMapper configMapper;

    @Autowired(required = false)
    private StringRedisTemplate redis;

    private String cacheKey(Long deviceId) { return "device:config:" + deviceId; }

    /** 查询设备所有配置（优先读缓存） */
    public ResultVo getAll(Long deviceId) {
        Map<String, String> map = null;
        if (redis != null) {
            map = redis.<String, String>opsForHash().entries(cacheKey(deviceId));
        }
        if (map == null || map.isEmpty()) {
            List<DeviceConfig> list = configMapper.selectList(new LambdaQueryWrapper<DeviceConfig>().eq(DeviceConfig::getDeviceId, deviceId));
            map = list.stream().collect(Collectors.toMap(DeviceConfig::getConfigKey, DeviceConfig::getConfigValue, (a,b)->a, LinkedHashMap::new));
            if (redis != null && !map.isEmpty()) {
                redis.opsForHash().putAll(cacheKey(deviceId), map);
                redis.expire(cacheKey(deviceId), Duration.ofMinutes(30));
            }
        }
        return ResultVo.success(map);
    }

    /** 批量设置配置（upsert），然后清缓存 */
    public ResultVo setAll(Long deviceId, Map<String, String> configs) {
        if (configs == null || configs.isEmpty()) return ResultVo.success();
        for (Map.Entry<String, String> e : configs.entrySet()) {
            // 先查是否存在，存在则更新，不存在则插入
            DeviceConfig exist = configMapper.selectOne(new LambdaQueryWrapper<DeviceConfig>()
                    .eq(DeviceConfig::getDeviceId, deviceId)
                    .eq(DeviceConfig::getConfigKey, e.getKey()));
            if (exist == null) {
                DeviceConfig c = new DeviceConfig();
                c.setDeviceId(deviceId);
                c.setConfigKey(e.getKey());
                c.setConfigValue(e.getValue());
                c.setConfigType("string");
                c.setCreateTime(new Date());
                c.setUpdateTime(new Date());
                configMapper.insert(c);
            } else {
                exist.setConfigValue(e.getValue());
                exist.setUpdateTime(new Date());
                configMapper.updateById(exist);
            }
        }
        if (redis != null) { redis.delete(cacheKey(deviceId)); }
        return ResultVo.success();
    }
}





